import path from 'path'
import electron, { BrowserWindow } from 'electron'
import loadURL from '@/utils/route'
import { executeJavaScript } from '@/utils/transfer'
import { initOptsMenu, reCreateMenu } from '@/electron/index'

const menuOpts = initOptsMenu()
const remote = require('@electron/remote')

const renders = [
  'clipboard',
  'contextBridge',
  'ipcRenderer',
  'nativeImage',
  'crashReporter'
]

function exposeBridgeAPI () {
  electron.contextBridge.exposeInMainWorld('electron', {
    remote,
    nativeImage: electron.nativeImage,
    ipcRenderer: electron.ipcRenderer,
    reCreateMenu: reCreateMenu,
    updateMenuOpts: menuOpts.updateOpts,
    getGlobal: remote.getGlobal,
    createSmartWindow: (winOpts: WinOpts) => {
      const browser: BrowserWindow = new remote.BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          contextIsolation: true,
          nodeIntegration: true,
          enableRemoteModule: true,
          preload: path.join(__dirname, 'preload.js')
        }
      })

      browser.on('close', () => {
        if (winOpts && winOpts.callback) winOpts.callback()
      })
      browser.on('ready-to-show', () => {
        // browser.webContents.openDevTools()

        browser.webContents.send('modal-complish', {
          name: 'longxiaobai'
        })

        browser.webContents.on('context-menu', () => {
          console.log('----- In auto Menu -----')
        })

        if (winOpts.execute) executeJavaScript(browser, winOpts.execute)
      })
      require('@electron/remote/main').enable(browser.webContents)

      loadURL(browser, winOpts)
    },
    triggerNotification () {
      const notify = new remote.Notification({
        title: '测试信息',
        body: '通知正文内容'
      })

      notify.on('close', () => {
        console.log('=== notify close ===')
      })

      if (notify) notify.show()
    },
    transferChannel (channel: string, fnCall: (data: any) => void) {
      electron.ipcRenderer.on(channel, (_, payload) => fnCall(payload))
    }
  })

  electron.contextBridge.exposeInMainWorld('transferAPI', {
    deleteAPI () {
      console.log('Del Alpha')
    }
  })
}

export default function transferAPI (INTEGRATION: string | undefined) {
  window.addEventListener('contextmenu', menuOpts.listener, false)
  if (INTEGRATION) {
    console.log('process.env.ELECTRON_NODE_INTEGRATION')
  } else {
    exposeBridgeAPI()
    for (const key of renders) {
      const qsFnAPI = Reflect.get(electron, key)
      electron.contextBridge.exposeInMainWorld(key, qsFnAPI)
    }
  }
}
